<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addUserApi, queryInfoApi, updateUserApi, deleteUserApi, queryAllApi } from '@/api/user'

//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

const searchUser = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})

//侦听searchUser中的date属性
watch(
  () => searchUser.value.date,
  (newValue, oldValue) => {
     if(newValue.length == 2){
      searchUser.value.begin = newValue[0]
      searchUser.value.end = newValue[1]
     }else {
      searchUser.value.begin = ''
      searchUser.value.end = ''
     }
  }
)

//声明token
const token = ref('')

onMounted(async () => {
  handleSearch()

  //加载localStorage存储的登录信息
  const loginUser =  localStorage.getItem('loginUser');
  if(loginUser){
    token.value = JSON.parse(loginUser).token
  }
})

//查询用户
const handleSearch = async () => {
  console.log('Search:', searchUser.value)
  const result = await queryPageApi(searchUser.value.name, searchUser.value.gender, searchUser.value.begin, searchUser.value.end, currentPage.value, pageSize.value);
  if(result.code){
    userList.value = result.data.rows
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchUser.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  handleSearch()
}

// 示例数据
const userList = ref([])

// 分页配置
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 操作处理
const handleEdit = async (id) => {
  
  const result = await queryInfoApi(id);
  if(result.code){
    dialogVisible.value = true
    dialogTitle.value = '修改用户'
    user.value = result.data
  }
  userFormRef.value.resetFields()
}

// 删除单个用户
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除用户
    const result = await deleteUserApi(id);
    if(result.code){
      ElMessage.success('删除用户成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}

//新增用户
const addUser = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增用户'
  user.value = {
    username: '',
    password: '',
    name: '',
    gender: '',
    phone: '',
    createTime: '',
    updateTime: '',
    remark: ''
  }
  userFormRef.value.resetFields()
}


//新增/修改表单
const userFormRef = ref(null)
const user = ref({
  username: '',
  password: '',
  name: '',
  gender: '',
  phone: '',
  createTime: '',
  updateTime: '',
  remark: ''
})

//表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')

//保存用户信息
const save = async () => {
  userFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      let result ;
      if(user.value.id){ //存在ID, 修改
        result = await updateUserApi(user.value);
      }else { //不存在ID, 新增
        result = await addUserApi(user.value);
      }
      if(result.code){
        ElMessage.success('操作成功')
        dialogVisible.value = false
        handleSearch()
      }else {
        ElMessage.error(result.msg)
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除
const deleteByIds = async () => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除用户
    const result = await deleteUserApi(selectedIds.value);
    if(result.code){
      ElMessage.success('删除用户成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}

</script>

<template>
  <h1>用户管理</h1> <br>
  <el-form :inline="true" :model="searchUser">
    <el-form-item label="姓名">
      <el-input v-model="searchUser.name" placeholder="请输入用户姓名"></el-input>
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchUser.gender" placeholder="请选择" style="width: 120px;">
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="2"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="创建日期">
      <el-date-picker
        v-model="searchUser.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addUser"> + 新增用户</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="userList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center"></el-table-column>
    <el-table-column type="index" label="序号" width="65" align="center"/>
    <el-table-column prop="username" label="用户名" width="120" align="center"></el-table-column>
    <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
    <el-table-column label="性别" width="60" align="center">
      <template #default="scope" >
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="150" align="center"></el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="170" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后更新时间" width="170" align="center"></el-table-column>
    <el-table-column prop="remark" label="备注" width="170" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[5, 10, 20, 30]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改用户的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="userFormRef" :model="user" :rules="rules" label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="user.password" placeholder="请输入密码，6-20个字" :show-password="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="user.name" placeholder="请输入姓名，2-10个字"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="user.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.name" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="user.remark" placeholder="请输入备注信息" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>

</template>

<style scoped>
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>